<?php
/**
 * 获取麦进斗订单
 * great time 2017/08/11
 * update time:2019.04.11
 */
require("/home/ryerp_api/getorder/interface.php");//公用接口
require_once("/home/ryerp_api/getorder/getorderproductoptionsid.php");
require_once('/home/paypal/GetTransactionDetails.php');


class GetMagentoOrder extends DB
{

	function __construct()
	{
		parent::__construct();
		echo "setp: 1 get account info!\n";
		$app_info = "select * from dlz_account_info where status='1'";
		$query = $this->db->query($app_info);
		//循环获取店铺信息，轮询获取订单
		echo "setp: foreach store\n";
		while ($row = $query->fetch()) {
//  [store_name] => OxeyeGirl Mall
//	[token] => r1ar4ckuxwivep0ocht9l59980b08eyo
//	[baseUrl] => https://www.oxeyegirl.com
//  [username] => api
//	[password] => rymht123321
//	[status] => 1
//  [isAuthorization] =>
//  [thirdname] => mall003
//	[memo] =>
//  [isdelete] => 1
//  [thirduser] => Oxeyegirl Mall
//	[thirdpwd] => fight123
//	[msg] => Dear $firstname,******
//	[paypal_user] => oxeyehair-beauty_api1.outlook.com
//	[paypal_pwd] => ZHSEBUVWEXCFDZUP
//	[paypal_signature] => AtF8R-n86CNhori-kL88smRDd1vBAnmQYg3u6jxx1kuuh15.hFqf.mXe
			$id_m = $row['id'];
			$store_name_m = $row['store_name'];
			$token_m = $row['token'];
			$baseUrl_m = $row['baseUrl'];
			$username_m = $row['username'];
			$password_m = $row['password'];
			$paypal_user = $row['paypal_user'];
			$paypal_pwd = $row['paypal_pwd'];
			$paypal_signature = $row['paypal_signature'];
			$Mazentop = new Mazentop($token_m, $baseUrl_m, $username_m, $password_m);//请求独立站
			echo "setp: 2 start get orderid [$store_name_m]\n";
			//取出订单列表中已存在的最大
			$sync_max_id = "select max(id) from dlz_attribute_all_id where store_id = '$id_m'";//2 242791
			$sync_max_query = $this->db->query($sync_max_id);
			while ($row = $sync_max_query->fetch()) {
				$maxid = $row[0];
			}
			$sync_id = "select orderid from dlz_attribute_all_id where id = '$maxid'";//242791 18380
			$sync_query = $this->db->query($sync_id);
			while ($row = $sync_query->fetch()) {
				$befoorderid = $row['orderid'];
//				print_r("获得最大的订单：" . $befoorderid);
			}
			//一次只去获取100单
			for ($i = 1; $i <= 20; $i++) {
				$startorderid = $befoorderid + $i;
				$status = $this->Getorderinfo($Mazentop, $id_m, $store_name_m, $orderid = $startorderid, $paypal_user,
					$paypal_pwd, $paypal_signature);
				$newadd = $startorderid - $befoorderid;
				$newadds = $newadd - 1;
				var_dump("数据:" . $status);
				if ($status == '2') {
					$nextstatus = '2';//2代表自定义值，未获取到数据，停止循环
					continue;
				} else {
					$nextstatus = '1';
				}
			}
			if ($nextstatus == '2' && $newadds !== 0) {
				/*同步记录*/
				//-1 代表此次未增加任何数据
				//$newadd = $startorderid-$befoorderid;
				$syncdata = [
					'new_add_num' => "$newadds",
					'store_name' => $store_name_m,
					'storeid' => $id_m,
					'lastorderid' => $startorderid,
					'orderidstoreid' => $startorderid . '-' . $id_m,
				];
				$table = 'dlz_sync_ordernums';
				echo "********************write sync info ******************** \n";

				$this->Getinsert($arrData = $syncdata, $table, $sync_data = "0");//
				//return true;
			}

		}
		$db = NULL;
	}


	/**
	 * [Getorderinfo description] 获取订单
	 * @param [type] $Mazentop     [API]
	 * @param [type] $id_m         [店铺id]
	 * @param [type] $store_name_m [店铺名称]
	 * @param [type] $db           [DB]
	 * @param [type] $orderid      [订单id]
	 */
	public function Getorderinfo($Mazentop, $id_m, $store_name_m, $orderid, $paypal_user, $paypal_pwd, $paypal_signature
	)
	{
		echo "\n+++++++++++++++++++订单+1+++++++++++++++++++++++\n";
		$UpdateTime = date('Y-m-d H:i:s');
		$data = $Mazentop->Byid($id = $orderid);
		if (array_key_exists('message', $data) || array_key_exists('error', $data)) {
			echo "\n";
			echo $orderid . "空的";
			return $status = '2';//获取不到数据，返回自定义数值
		}
		echo "order_id=" . $data['increment_id'] . "\n";
		$increment_id = $data['increment_id'];//订单号
		$entity_id = $data['entity_id'];//order
		$store_id = $id_m;//店铺id
		$store_name_str = $data['store_name'];//店铺名字
		$store_name = str_replace(["\r\n", "\r", "\n"], " ", $store_name_str);
		$status = $data['status'];//订单状态
		$base_grand_total = $data['base_grand_total'];//订单总金额
		$base_shipping_amount = $data['base_shipping_amount'];//运费
		$base_total_paid = !empty($data['base_total_paid']) ? $data['base_total_paid'] : NULL;//付款金额
		$order_currency_code = $data['order_currency_code'];//订单币种
		$total_item_count = $data['total_item_count'];//子订单数量
		$total_qty_ordered = $data['total_qty_ordered'];//产品数量
		$subtotal = $data['subtotal'];//总金额包括运费
		$discount_amount = $data['discount_amount'];//总折扣
		$discount_description = !empty($data['discount_description']) ? $data['discount_description'] : NULL;//折扣名称
		$weight = $data['weight'];//产品总重量
		$created_at = $data['created_at'];//订单创建时间
		$updated_at = $data['updated_at'];//订单修改时间
		$remote_ip = $data['remote_ip'];//登录ip
		$customer_is_guest = $data['customer_is_guest'];//是否是游客
		$items = $data['items'];//子订单信息
		/*
		foreach ($items as $key => $value) {
			$child_created_at = $value['created_at'] ;//创建时间
			$child_name = $value['name'] ;//商品名称
			$child_sku = $value['sku'] ;//商品名称
			$child_order_id = $value['order_id'] ;//订单id
			$child_updated_at = $value['updated_at'] ;//更新时间
	   }
	   */
		$billing_address = $data['billing_address'];//账单地址
		$billing_address_address_type = $billing_address['address_type'];//账单
		$billing_address_city = addslashes($billing_address['city']);//城市
		$billing_address_company = !empty($billing_address['company']) ? addslashes($billing_address['company']) : NULL;//公司
		$billing_address_country_id = $billing_address['country_id'];//国家编码
		$billing_address_email = addslashes($billing_address['email']);//邮件地址
		$billing_address_firstname = addslashes($billing_address['firstname']);//名字
		$billing_address_lastname = addslashes($billing_address['lastname']);//姓氏
		$billing_address_postcode = addslashes($billing_address['postcode']);//邮编
		$billing_address_region = addslashes($billing_address['region']);//地区
		$billing_address_region_code = $billing_address['region_code'];//地区编码
		$billing_address_street = $billing_address['street'];//街道
		$billing_street = addslashes(implode(" ", $billing_address_street));
		$billing_address_telephone = addslashes($billing_address['telephone']);//电话
		/***买家信息写入数据库****/
		$BuyerData = [
			'store_id' => $id_m,
			'store_name' => $store_name_m,
			'telephone' => $billing_address_telephone,
			'country' => $billing_address_country_id,
			'region' => $billing_address_region,
			'email' => $billing_address_email,
			'firstName' => $billing_address_firstname,
			'lastName' => $billing_address_lastname,
			'remote_ip' => $remote_ip,
			'is_guest' => $customer_is_guest,
			'updatetime' => $UpdateTime,
		];
		$table_buyer = 'dlz_buyer_info';
		echo "********************write mysql  buyer******************** \n";
		$this->Getinsert($arrData = $BuyerData, $table = $table_buyer, $sync_data = "0");//

		/******付款部分**********/
		$payment = $data['payment'];//付款
		$payment_account_status = $payment['account_status'];//账户状态
		$additional_information = $payment['additional_information'];//付款返回值
		$pay_info_status = !empty($additional_information[0]) ? $additional_information[0] : NULL;//
		$pay_info_nul = !empty($additional_information[1]) ? $additional_information[1] : NULL;
		$pay_id = !empty($additional_information[2]) ? $additional_information[2] : NULL;//Payer ID
		$pay_Email = !empty($additional_information[3]) ? $additional_information[3] : NULL;//Payer Email:
		$pay_Status = !empty($additional_information[4]) ? $additional_information[4] : NULL;//Payer Status:
		$pay_address_status = !empty($additional_information[5]) ? $additional_information[5] : NULL;//Payer Address Status:
		$pay_LastCorrelationID = !empty($additional_information[6]) ? $additional_information[6] : NULL;//相关id
		$pay_EC = !empty($additional_information[8]) ? $additional_information[8] : NULL;//未知参数
		$pay_MPE = !empty($additional_information[11]) ? $additional_information[11] : NULL;//Merchant Protection Eligibility
		$pay_result = !empty($additional_information[12]) ? $additional_information[12] : NULL;//支付结果

		/*
			   $payment_amount_ordered = $payment['amount_ordered'];//应付款金额
			  // $payment_base_amount_ordered = $payment['base_amount_ordered'];//实际付款金额
			   $payment_shipping_amount = $payment['shipping_amount'];//应付邮费金额
			   //$payment_base_shipping_amount = $payment['base_shipping_amount'];//实际邮费金额
			   */
		$payment_method = $payment['method'];//付款方式
		$amount_refunded = !empty($payment['amount_refunded']) ? $payment['amount_refunded'] : NULL;//退款金额
		$payment_last_trans_id = !empty($payment['last_trans_id']) ? $payment['last_trans_id'] : NULL;//交易id
		/***********写入数据库**************************/
		$Order_Data = [
			'increment_id' => $increment_id,
			'store_id' => $store_id,
			'store_name' => $store_name,
			'status' => $status,
			'subtotal' => $subtotal,
			'base_grand_total' => $base_grand_total,
			'base_shipping_amount' => $base_shipping_amount,
			'base_total_paid' => $base_total_paid,
			'discount_amount' => $discount_amount,
			'discount_description' => $discount_description,
			'order_currency_code' => 'USD',//$order_currency_code,
			'amount_refunded' => $amount_refunded,
			'payment_method' => $payment_method,
			'payment_last_trans_id' => $payment_last_trans_id,
			'total_item_count' => $total_item_count,
			'total_qty_ordered' => $total_qty_ordered,
			'weight' => $weight,
			'created_at' => $created_at,
			'updated_at' => $updated_at,
			'updatetime' => $UpdateTime,

		];
		$table = 'dlz_order_info';//香港服订单表
		echo "********************write mysql order******************** \n";
		$this->Getinsert($arrData = $Order_Data, $table, $sync_data = '0');//
		echo "********************通过paypal 获取净额******************** \n";
		/***********通过paypal 获取净额***************/
		echo "********************" . $payment_last_trans_id . "******************** \n";
		if (!empty($payment_last_trans_id)) {
			$Paypledetail = new Paypledetail();
			$netdata = $Paypledetail->GetOrderPaypalNet($paypalid = $payment_last_trans_id, $paypal_user, $paypal_pwd,
				$paypal_signature);
			$this->update($table = 'dlz_order_info', $arrData = $netdata, $filed = 'payment_last_trans_id',
				$fileddata = $payment_last_trans_id);
			// Getinsert($arrData=$netdata,$table='dlz_order_info',$db,$sync_data="0");//
		}

		$extension_attributes = $data['extension_attributes']['shipping_assignments'];//扩展信息
		/*******************解析接口******************/
		echo '扩展信息' . json_encode($data);
		if (is_array($data)) {
			foreach ($extension_attributes as $key => $value) {
				$extension_shipping = $value['shipping']['address'];//物流信息
				$extension_attributes_address_type = $extension_shipping['address_type'];//地址类型
				$extension_attributes_city = addslashes($extension_shipping['city']);//城市
				$extension_attributes_company = !empty($extension_shipping['company']) ? addslashes($extension_shipping['company']) : NULL;//公司
				$extension_attributes_country_id = $extension_shipping['country_id'];//国家编码
				$extension_attributes_email = addslashes($extension_shipping['email']);//邮件地址
				$extension_attributes_firstname = addslashes($extension_shipping['firstname']);//名字
				$extension_attributes_lastname = addslashes($extension_shipping['lastname']);//姓氏
				$extension_attributes_postcode = addslashes($extension_shipping['postcode']);//邮编
				$extension_attributes_region = addslashes($extension_shipping['region']);//地区
				$extension_attributes_region_code = $extension_shipping['region_code'];//地区编码
				$extension_attributes_street = $extension_shipping['street'];//街道
				$shipping_street = addslashes(implode("__", $extension_attributes_street));
				$extension_attributes_telephone = addslashes($extension_shipping['telephone']);//电话
				$extension_shipping = $value['shipping']['total'];//物流金额
				$shipping_amount = $extension_shipping['shipping_amount'];
				/***寄送地址写入数据库****/
				$ShippingData = [
					'increment_id' => $increment_id,
					'store_id' => $id_m,
					'store_name' => $store_name_m,
					'shipping_amount' => $shipping_amount,
					'order_currency_code' => $order_currency_code,
					'shipping_street' => $shipping_street,
					'city' => $extension_attributes_city,
					'company' => $extension_attributes_company,
					'entity_id' => $entity_id,
					'country_id' => $extension_attributes_country_id,
					'email' => $extension_attributes_email,
					'firstname' => $extension_attributes_firstname,
					'lastname' => $extension_attributes_lastname,
					'postcode' => $extension_attributes_postcode,
					'region' => $extension_attributes_region,
					'region_code' => $extension_attributes_region_code,
					'telephone' => $extension_attributes_telephone,
					'updatetime' => $UpdateTime,
					'shopid_ent' => $increment_id . '_' . $entity_id,
				];

				$table_ship = 'dlz_shipping_info';
				echo "********************write mysql  shipping******************** \n";
				//print_r($ShippingData);
				$this->Getinsert($arrData = $ShippingData, $table = $table_ship, $sync_data = "0");
				$Getproduct = new Getproduct();
				$extension_attributes_shipping_assignments_items = $value['items'];//订单物流货品信息
				foreach ($extension_attributes_shipping_assignments_items as $key => $values) {
//					$items_created_at = $values['created_at'];//订单物流货品信息
//					$items_name = $values['name'];//产品名
//					$items_product_type = $values['product_type'];//产品类型
//					$items_store_id = $values['store_id'];//商店id
//					$items_created_at = $values['created_at'];//创建时间
//					$items_updated_at = $values['updated_at'];//更新时间
					$order_id = $values['order_id'];//orderid
					$items_product_id = $values['product_id'];//产品id
					$item_price = $values['price'];//单个item产品总价
					$items_item_id = $values['item_id'];//item_id 20077  20076
					$items_sku = $values['sku'];//sku
					//通过item id 去获取相应的订单信息
					//$Mazentop 46356 M000071764 $this->db 2
					$rest = $Getproduct->byItemIdGetProduct($Mazentop, $item_id = $items_item_id, $increment_id,
						$this->db, $id_m);
					if (!$rest) {
						//break;
						continue;
					}
					$qty_ordered = $values['qty_ordered'];//条数
					/***买家信息写入数据库****/
					$ProductitemData = [
						'store_id' => $id_m,
						'store_name' => $store_name_m,
						'increment_id' => $increment_id,
						'product_id' => $items_product_id,
						'sku' => $items_sku,
						'item_id' => $items_item_id,
						'orderid' => $order_id,
						'storeanditem' => $id_m . '_' . $items_item_id,
						'price' => $item_price,
						'pice_or_lotnums' => $qty_ordered,
						'sync_status' => '0',//默认给2,因为未找到 同步option后 不改变为0，目前先给0
						'updatetime' => $UpdateTime,
					];
					$table_item = 'dlz_attribute_all_id';
					echo "********************write mysql  items******************** \n";
					$this->Getinsert($arrData = $ProductitemData, $table = $table_item, $sync_data = "0");//
					$insert_statu_Y = "update dlz_order_info set orderid='$order_id' where increment_id='$increment_id'";
					$checkStatus = $this->db->exec($insert_statu_Y);//如果出现 400 500，则不在推送。storeid
				}//extension_attributes_shipping_assignments_items 循环结尾
			}//shipping_assignments 循环结尾
			echo "++++++++++++++++++end++++++++++++++++++++\n";
			return 3;
		} else {
			return 2;
		}
	}
}


$GetMagentoOrder = new GetMagentoOrder();


